<script setup lang="ts">
  import { ref, onBeforeMount, watch } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { useModalBinder } from '@/hooks/arco/useModalBinder';
  import * as Lodash from 'lodash';
  import { queryRoles, giveStaffPermissions } from '@/api/permission';

  const currentStaffId = ref('');
  const currentPermissions = ref([]);
  const rols = ref<any[]>([]);
  const selectRoles = ref<any[]>([]);

  const binder = useModalBinder(
    (record) => {
      currentStaffId.value = record.staffId;
      currentPermissions.value = Lodash.cloneDeep(record.roles);
      // console.log(currentPermissions.value);
      binder.setTitle('功能权限');
    },
    {
      showFooter: true,
    }
  );

  const onBeforeOk = (done: any) => {
    giveStaffPermissions(currentStaffId.value, selectRoles.value)
      .then((res) => {
        done(true);
        Message.success('设置成功');
        binder.hideModal();
        binder.triggerSuccess(res);
      })
      .catch(() => {
        done(false);
      });
  };

  const handleRolesChange = (values: string[]) => {
    // console.log(values);
    // console.log(selectRoles.value)
  };

  onBeforeMount(() => {
    queryRoles()
      .then((res) => {
        rols.value = res;
      })
      .catch((err) => {});
  });

  defineExpose(binder.expose);

  watch(
    () => currentPermissions.value,
    (newVal) => {
      newVal.forEach((roleItem: any) => {
        if (!selectRoles.value.includes(roleItem.id)) {
          selectRoles.value.push(roleItem.id);
        }
      });
    },
    { immediate: true, deep: true }
  );
</script>

<template>
  <div class="m-employee-permission">
    <a-modal draggable v-bind="binder.bindProps" @before-ok="onBeforeOk">
      <div>
        <div
          ><span style="font-weight: 600">请选择此账号的功能权限组：</span></div
        >
        <a-checkbox-group
          v-model="selectRoles"
          class="m-ep-group"
          @change="handleRolesChange"
        >
          <a-checkbox
            v-for="(item, index) of rols"
            :key="'mp-role+' + index"
            class="m-ep-item"
            :class="{ selected: selectRoles.includes(item.id) }"
            :value="item.id"
            >{{ item.name }}</a-checkbox
          >
        </a-checkbox-group>
      </div>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
  .m-employee-permission {
  }

  .m-ep-group {
    margin-top: 15px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    row-gap: 10px;
    padding: 0 5px;

    .m-ep-item {
      padding: 8px 24px 8px 20px;
      border: 2px solid var(--color-neutral-4);
      border-radius: 4px;
      box-sizing: border-box;
    }

    .selected {
      border: 2px solid rgb(var(--primary-3));
    }
  }
</style>
